<template>
  <div style="width: 100%;">
    <!-- <el-card> -->
    <div style="margin-bottom: 10px; ">
      <el-form :inline="true">
        <el-row :gutter="5" class="formRow">
          <el-col :span="10" class="formCol" style="margin-left: 5%;">
            <el-form-item label="Metric" class="formLabel">
              <el-select v-model="Form.metric" class="formSelect" size="small " placeholder="请选择Metric" clearable filterable @change="metricChange">
                <el-option v-for="metric in metric_list" :key="metric.id" :label="metric.name" :value="metric.name" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10" class="formCol">
            <el-form-item label="聚合函数" class="formLabel">
              <el-select v-model="Form.aggregator" class="formSelect" size="small " placeholder="请选择Aggregator" clearable filterable>
                <el-option v-for="aggregator in aggregators_list" :key="aggregator.id" :label="aggregator" :value="aggregator" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="5" class="formRow">
          <el-col :span="20" class="formCol" style="margin-left: 5%;">
            <label class="tagLabel">标签</label>
            <div id="showTagsDiv" class="tagDiv" />
            <div v-show="isShow" id="tagSelectDiv" class="tagDiv">
              <el-select v-model="Tags.tag_key" class="tagSelect" size="small " placeholder="选择键" clearable filterable @change="tagKeyChange">
                <el-option v-for="(tag_key, i) in key_list" :key="i" :label="tag_key" :value="tag_key" />
              </el-select>
              <el-select v-model="Tags.tag_val" class="tagSelect" size="small " placeholder="选择值" clearable filterable>
                <el-option v-for="(tag_val, j) in val_list" :key="j" :label="tag_val" :value="tag_val" />
              </el-select>
              <el-button type="infor" size="small " icon="el-icon-plus" @click="addTag">添加标签</el-button>
            </div>
            <el-button v-show="bottonShow" style="margin-left: 20px; margin-top: 7px; float:left;" type="success" size="small " icon="el-icon-plus" @click="addTagsInit" />
          </el-col>
        </el-row>
        <el-row :gutter="5" class="formRow">
          <el-col :span="20" class="formCol" style="margin-left: 5%;">
            <el-form-item label="时间段" prop="time" class="formLabel">
              <el-col style="margin-left: 15%;">
                <el-date-picker
                  v-model="Form.defaulttimeperiod"
                  type="datetimerange"
                  :picker-options="pickerOptions"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  align="left"
                  size="small "
                />
                <!-- <el-date-picker v-model="Form.start" placeholder="开始时间" size="small " type="datetime" />
                  <span>至</span>
                  <el-date-picker v-model="Form.end" placeholder="结束时间" size="small " type="datetime" /> -->
              </el-col>
            </el-form-item>
          </el-col>
          <el-col :span="2" style="margin-left: 2%;">
            <el-button type="primary" size="small " icon="el-icon-search" @click="search">查询</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div>
      <el-row :gutter="10">
        <el-col :span="24">
          <div id="lineChart_1" :style="{width: '98%', height: '400px'}" />
        </el-col>
      </el-row>
    </div>
    <div style="margin-top: 10px; ">
      <el-table
        v-if="tableShow"
        ref="singleTable"
        :data="tableData"
        border
        size="small "
        style="width: 100%;"
        highlight-current-row
        :show-header="false"
      >
        <template v-for="(value,index) in tableHeader">
          <el-table-column :key="index" :prop="value" :label="value" />
        </template>
      </el-table>
    </div>
    <!-- </el-card> -->
  </div>
</template>

<script>
// import axios from 'axios'
import axiosservice from '@/utils/CommonData.js'
import { formatDate } from '@/utils/time.js'
// import '@/assets/css/metricSearch.css'
// 在组件引入基本模板
import * as echarts from 'echarts'
// 在组件引入柱状图组件
require('echarts/lib/chart/line')
export default {
  name: 'Echarts',
  data() {
    return {
      metrictagstree: null,
      colorArray: ['#3499DD', '#32C5D3', '#E7505A', '#C59F46', '#8F44AD', '#70AD46', '#CB660A', '#A7B7CC', '#3499DD', '#32C5D3', '#E7505A', '#C59F46', '#8F44AD', '#70AD46', '#CB660A', '#A7B7CC'],	//
      status: ' ',
      isShow: false,
      bottonShow: true,
      metric_list: [],
      key_list: [],
      val_list: [],
      aggregators_list: ['none', 'mult', 'p90', 'zimsum', 'mimmax', 'sum', 'p50', 'p95', 'ep99r7', 'pfsum', 'p75', 'p99', 'ep99r3', 'ep95r7', 'min', 'avg', 'ep75r7', 'dev', 'ep95r3', 'ep75r3', 'ep50r7', 'ep90r7', 'mimmin', 'p999', 'ep50r3', 'ep90r3', 'ep999r7', 'last', 'max', 'count', 'diff', 'median', 'squareSum', 'ep999r3', 'first'],
      // defaulttimeperiod: [new Date(2021, 5, 1, 0, 0), new Date(2021, 6, 1, 0, 0)],
      pickerOptions: {
        shortcuts: [{
          text: '最近一天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      tableData: [],
      tableShow: false,
      tagHtml: '',
      // 动态列头header
      tableHeader: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60'],
      Form: { // start=1616848429&end=1616848489&m=sum:testmetric1&(tag1=0,tag2=1)
        defaulttimeperiod: [new Date(new Date() - 24 * 60 * 60 * 1000), new Date()],
        metric: '',
        tag: '',
        aggregator: 'sum'
      },
      Tags: {
        tag_key: '',
        tag_val: ''
      }
    }
  },
  created() {
    const _this = this
    window.delTag = _this.delTag
  },
  mounted() {
    // const loading = this.$loading({
    //   lock: true, // lock的修改符--默认是false
    //   text: '拼命加载中，请稍候...', // 显示在加载图标下方的加载文案
    //   background: 'rgba(0,0,0,0.8)', // 遮罩层颜色
    //   spinner: 'el-icon-loading' // 自定义加载图标类名
    // })
    this.getMetrics()
    // this.getTagKeys()
    // this.getTagValues()
    // this.getMetricTagTree()
    // loading.close()
  },
  methods: {
    metricChange(metric) {
      console.log('metricChange', metric)
      this.key_list.splice(0)
      this.val_list = []
      if (this.metrictagstree[metric]) {
        for (var p1 in this.metrictagstree[metric]) {
          this.key_list.push(p1)
        }
      }
      console.log('key_list', this.key_list)
      this.Tags.tag_key = ''
      this.Tags.tag_val = ''
    },
    tagKeyChange(tagkey) {
      console.log('tagKeyChange', tagkey)
      this.val_list = this.metrictagstree[this.Form.metric][tagkey]
      console.log('val_list', this.val_list)
      this.Tags.tag_val = ''
      console.log('this.Tags', this.Tags)
    },
    getMetricTagTree() {
      axiosservice({
        url: '/metrictagstree',
        method: 'get'
      })
        .then((res) => {
          if (res.status == 200) {
            if (res.data.code == 200) {
              this.metrictagstree = JSON.parse(res.data.data)
              this.metricChange(this.Form.metric)
            }
          }
        })
        .catch((error) => {
          console.log(error)
          this.$message.error('获取tag数据失败!')
        })
    },
    addTagsInit() {
      this.isShow = true
      this.bottonShow = false
    },

    addTag() {
      // var id = this.Tags.tag_key + '_' + this.Tags.tag_val
      var text = this.Tags.tag_key + '=' + this.Tags.tag_val
      if (text == '=') {
        this.isShow = false
        this.bottonShow = true
        return
      }
      if (this.Form.tag == '') {
        this.Form.tag = text
      } else {
        this.Form.tag += ',' + text
      }
      //  this.tagHtml += '<el-button type="primary" size="small " @click="delTag" icon="el-icon-remove">'+this.Tags.tag_key+'='+this.Tags.tag_val+'</el-button>'; //onClick="delTag"
      this.tagHtml += '<label style="margin-left:5px;border: 1px solid #00557f;">' + text + '<i style="cursor:pointer;padding-left:5px;" class="remove el-icon-remove" onClick="delTag(\'' + text + '\')" ></i> </label>'// <button style="cursor:pointer;padding-left:5px;"  onClick="delTag(\''+text+'\')">'+text+'<i style="cursor:pointer;padding-left:5px;"  class="remove el-icon-remove" @click="delTag(\''+this.Tags.tag_key+'='+this.Tags.tag_val+'\')"></i></button>';
      this.isShow = false
      this.bottonShow = true
      var div = document.getElementById('showTagsDiv')
      div.innerHTML = this.tagHtml
    },
    delTag(id) {
      var text = id// id.replace("_","=");
      var tag1 = this.Form.tag.replace(text + ',', '')
      var tag2 = this.Form.tag.replace(',' + text, '')
      // alert(this.Form.tag);
      if (this.Form.tag == tag1) {
        if (this.Form.tag == tag2) {
          this.Form.tag = this.Form.tag.replace(text, '')
        } else {
          this.Form.tag = this.Form.tag.replace(',' + text, '')
        }
      } else {
        this.Form.tag = this.Form.tag.replace(text + ',', '')
      }
      //  alert(this.Form.tag);
      var delHtml = '<label style="margin-left:5px;border: 1px solid #00557f;">' + text + '<i style="cursor:pointer;padding-left:5px;" class="remove el-icon-remove" onClick="delTag(\'' + id + '\')" ></i> </label>'// <button style="cursor:pointer;padding-left:5px;"  onClick="delTag(\''+text+'\')">'+text+'<i style="cursor:pointer;padding-left:5px;"  class="remove el-icon-remove" @click="delTag(\''+this.Tags.tag_key+'='+this.Tags.tag_val+'\')"></i></button>';
      // '<button onClick="delTag(\''+this.Tags.tag_key+'='+this.Tags.tag_val+'\')">'+this.Tags.tag_key+'='+this.Tags.tag_val+'<i style="cursor:pointer;padding-left:5px;" class="remove el-icon-remove" @click="delTag(\''+this.Tags.tag_key+'='+this.Tags.tag_val+'\')"></i></button>';//'<label style="margin-left:5px;border: 1px solid #00557f;" value="'+text+'"> <i style="cursor:pointer;padding-left:5px;" class="remove el-icon-remove" @click="delTag(\''+id+'\')"></i></label>';

      this.tagHtml = this.tagHtml.replace(delHtml, '')
      this.isShow = false
      this.bottonShow = true
      var div = document.getElementById('showTagsDiv')
      div.innerHTML = this.tagHtml
    },
    getMetrics() {
      // axios.get('/api/metrics')
      axiosservice({
        url: '/api/metrics',
        method: 'get'
      })
        .then((res) => {
          if (res.status == 200) {
            const data = res.data
            for (var index in data) {
              this.metric_list.push({
                'id': index,
                'name': data[index]
              })
            }
            this.Form.metric = data[0] // 默认值取第一个
            this.getMetricTagTree()
          }
        })
        .catch((error) => {
          console.log(error)
          this.$message.error('获取metrics数据失败!')
        })
    },
    getTagKeys() {
      // axios.get('/api/tagk')
      axiosservice({
        url: '/api/tagk',
        method: 'get'
      })
        .then((res) => {
          if (res.status == 200) {
            const data = res.data
            for (var index in data) {
              this.key_list.push({
                'id': index,
                'name': data[index]
              })
            }
          }
        })
        .catch((error) => {
          console.log(error)
          this.$message.error('获取tag-key数据失败!')
        })
    },

    getTagValues() {
      // axios.get('/api/tagv')
      axiosservice({
        url: '/api/tagv',
        method: 'get'
      })
        .then((res) => {
          if (res.status == 200) {
            const data = res.data
            for (var index in data) {
              this.val_list.push({
                'id': index,
                'name': data[index]
              })
            }
          }
        })
        .catch((error) => {
          console.log(error)
          this.$message.error('获取tag-value数据失败!')
        })
    },
    search() {
      // /opentsdb/query?start=1616848429&end=1616848489&m=sum:testmetric1&tags=tag1:0,tag2:1
      const s = Math.round(this.Form.defaulttimeperiod[0] / 1000)// 1616848429
      const e = Math.round(this.Form.defaulttimeperiod[1] / 1000)// 1616848489
      const a = this.Form.aggregator// sum
      const m = this.Form.metric// testmetric1
      const t = this.Form.tag.replace(/=/g, ':')// tag1=0,tag2=1

      this.tableData = []
      // start='+s+'&end='+e+'&m='+a+':'+m+'&'+t)
      const url = '/opentsdb/query?start=' + s + '&end=' + e + '&m=' + a + ':' + m + '&(' + t + ')'
      // axios.get(url)
      axiosservice({
        url,
        method: 'get'
      })
        .then((res) => {
          if (res.status == 200) {
            const result = res.data[0].dps
            const data = []
            const xData = []
            for (var key in result) {
              const keyNew = formatDate(new Date(key * 1000), 'MM-dd hh:mm:ss')
              xData.push(keyNew)
              data.push(result[ key ].toFixed(2)) // 注意是 [  ]
            }
            this.lineDraw('lineChart_1', 'metric连接数趋势', xData, data)
            this.tableData.push(xData)
            this.tableData.push(data)
            this.tableShow = true
          }
        })
        .catch((error) => {
          console.log(error)
          this.$message.error('metric连接数趋势调用失败!')
        })
    },
    lineDraw(id, title, xData, data) {
      // 基于准备好的dom，初始化echarts实例
      echarts.dispose(document.getElementById(id))
      const line = echarts.init(document.getElementById(id))
      // 绘制图表配置
      const option = {
        grid: {
          top: 50,
          bottom: 40,
          left: 50,
          right: 40
        },
        color: '#3499DD',
        title: {
          text: title
        },
        tooltip: {
          trigger: 'axis'
        },
        toolbox: {
          show: true,
          feature: {
            dataZoom: {
              yAxisIndex: 'none'
            },
            dataView: { readOnly: false },
            magicType: { type: ['line', 'bar'] },
            restore: {},
            saveAsImage: {}
          }
        },
        xAxis: {
          type: 'category',
          data: xData,
          boundaryGap: false
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value}'
          }
        },
        series: [
          {
            name: title,
            type: 'line',
            data: data,
            // smooth: true,
            markPoint: {
              data: [
                { type: 'max', name: '最大值', itemStyle: { color: '#E7505A' }},
                { type: 'min', name: '最小值', itemStyle: { color: '#70AD46' }}
              ]
            }
          }
        ]
      }
      // 窗口大小自适应方案
      line.setOption(option)
      setTimeout(function() {
        window.onresize = function() {
          line.resize()
        }
      }, 200)
    }
  }
}

</script>

<style>
@charset "UTF-8";
.formRow{
  height: 40px;
  line-height: 40px;
  margin-bottom: 1px;
}
.formCol{
  height: 40px;
  line-height: 40px;
/* background-color:#e8e8e8; */
}
.formItem{
  width: 100%;
  text-align: left;
}
.formLabel{
  margin-right: 50px;
  font-size:14px;
  padding-left: 10px;
  text-align: left;
  width: 100%;
  border: 1px solid #F8F6F6;
}

.formSelect{
  margin-left: 40%;
  width: 120%;
}
.tagLabel{
  padding-left: 10px;
  text-align: left;
  float:left;
}
.tagSelect{
  /* margin-left: 10px; */
  width: 100px;

}
.tagDiv{
  height: 40px;
  line-height: 40px;
  float:left;
  margin-left: 13px;
}
.formTag{
  width: 100%;
  margin-left: 20%;
}

.formTime{
  width: 100%;
  margin-left: 20%;
}

</style>
